<template>
  <div class="list-warp">
    <p class="list-title" v-if="title">{{title}}</p>
    <div
      class="list-scroll"
      ref="warp"
      :style="{ height: scrollHeight + 'px' }"
      @mouseenter="handleEnter"
      @mouseleave="handleLeave"
    >
      <ul class="item">
        <li v-for="(item, index) in list" :key="index" @click="handleClick(item)">
          <span class="index" v-text="index + 1"></span>
          <span class="title" v-text="item.title"></span>
        </li>
      </ul>
      <ul :class="['item', { hide: !openScroll }]">
        <li v-for="(item, index) in list" :key="index" @click="handleClick(item)">
          <span class="index" v-text="index + 1"></span>
          <span class="title" v-text="item.title"></span>
        </li>
      </ul>
      </div>
  </div>
</template>

<script>
export default {
  name: 'ListScroll',
  props: {
    title: {
      type: String,
      default: '',
    },
    scrollHeight: {
      type: Number,
      default: 200,
    },
    list: {
      type: Array,
      default: () => [],
    },
    speed: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      reqFrame: null,
      height: 0,
      openScroll: true,
      isMoved: false,
    };
  },
  computed: {
    // 第一个slot
    ele0() {
      return this.$refs.warp.children[0];
    },
    // 第二个slot
    ele1() {
      return this.$refs.warp.children[1];
    },
  },
  watch: {
    list() {
      this.reset();
    },
  },
  mounted() {
    setTimeout(this.init, 30);
  },
  methods: {
    handleClick(item) {
      this.$emit('item-click', item);
    },
    reset() {
      this.cancel();
      setTimeout(this.init, 0);
    },
    init() {
      this.cancel();
      this.$nextTick(() => {
        // 在盒子内容高度小于可视高度时不滚动
        if (this.scrollHeight < this.ele0.clientHeight) {
          this.start(this.height);
          this.openScroll = true;
        } else {
          this.openScroll = false;
        }
      });
    },
    cancel() {
      window.cancelAnimationFrame(this.reqFrame);
    },
    handleEnter() {
      /** 鼠标移入停止滚动 */
      // this.openScroll = false;
      this.isMoved = true;
      this.cancel();
    },
    handleLeave() {
      this.isMoved = false;
      this.$nextTick(() => {
        this.start(this.height);
      });
    },
    // 滚动方法
    start(height) {
      this.ele0.style = `transform:translateY(${height}px);`;
      this.ele1.style = `height:${this.scrollHeight}px;transform:translateY(${height}px);overflow: hidden;`;
      if (Math.abs(height) >= this.ele0.clientHeight) {
        this.height = 0;
      } else {
        this.height -= this.speed;
      }
      if (!this.openScroll || this.isMoved) return;
      this.reqFrame = window.requestAnimationFrame(() => {
        this.start(this.height);
      });
    },
  },
};
</script>

<style scoped>
     @import './index.css';
</style>
